var editor = null;
var submitting = false;
var username = document.getElementById('username').value;
var langMap = new Array();
/*
language0=All
language1=MS C++
language2=MS C
language3=GNU C++
language4=GNU C
language5=Java
language6=C#
language7=F#
language8=Pascal
language9=Python
language10=Ruby
language11=Perl
language12=Lua
language13=Tcl
language14=Pike
language15=Haskell
language16=PHP
language17=BrainFuck
language18=Befunge
language19=GO
language20=Scala
language21=JavaScript
language22=Groovy
language23=Objective-c
*/
langMap[0] = "null";
langMap[1] = "cpp";
langMap[2] = "cpp";
langMap[3] = "cpp";
langMap[4] = "cpp";
langMap[5] = 'java';
langMap[6] = "csharp";
langMap[7] = "fsharp";
langMap[8] = "pascal";
langMap[9] = "python";
langMap[10] = "ruby";
langMap[11] = "perl";
langMap[12] = "lua";
langMap[13] = "tcl";
langMap[14] = "pike";
langMap[15] = "perl";
langMap[16] = "php";
langMap[17] = "java";
langMap[18] = "java";
langMap[19] = "go";
langMap[20] = "java";
langMap[21] = "javascript";
langMap[22] = "java";
langMap[23] = "objective-c";
langMap[24] = "cpp";
langMap[25] = "cpp";
langMap[26] = "cpp";
langMap[27] = "cpp";
langMap[28] = "cpp";
langMap[29] = "cpp";

var themeTbl = new Array();
themeTbl[0] = "vs";
themeTbl[1] = "vs-dark";
themeTbl[2] = "hc-black";

$(document).ready(function () {
	require.config({paths:{'vs':'/js/monaco-editor/min/vs'}});
	require(['vs/editor/editor.main'], function() {
		$(".theme-picker").change(function() {
			changeTheme();
		});
		$(".fontsize-picker").change(function() {
			changeFontsize();
		});
		$(".lang-choice").change(function() {
			changeLanguage();
		});
		$(".wordwrap-column").change(function() {
			changeWordWrap();
		});

		var problemId = document.getElementById('problemId').value;
		var contestId = document.getElementById('contestId').value;
		var name = username + "_lang_" + contestId + "_" + problemId;
		var language = 'cpp'
		var lang = window.localStorage.getItem(name);
		if (lang != null) {
			language = langMap[lang];
		}

		name = username + "_ide_theme";
		var theme = window.localStorage.getItem(name);
		if (theme == null) {
			theme = '0';
		}
		$('#theme-picker').val(theme);

		name = username + "_ide_fontsize";
		var fontSize = window.localStorage.getItem(name);
		if (fontSize == null) {
			fontSize = '13';
		}
		$('#fontsize-picker').val(fontSize);

		name = username + "_ide_wordwrapcolume";
		var wordwrapcolume = window.localStorage.getItem(name);
		if (wordwrapcolume == null) {
			wordwrapcolume = '80';
		}
		$('#wordwrap-column').val(wordwrapcolume);
		var wordwrapminified = 'true';
		var wordwrap = 'wordWrapColumn';
		if (wordwrapcolume == '0') {
			wordwrapminified = 'false';
			wordwrap = 'off';
		}

		editor = monaco.editor.create(document.getElementById("source"), {
			value: [].join('\n'),
			language: language,
			fontSize: fontSize+"px",
			theme: themeTbl[theme],
			wordWrap: wordwrap,
			wordWrapColumn: wordwrapcolume,
			wordWrapMinified: wordwrapminified,
		});

		function changeTheme() {
			var newTheme = document.getElementById('theme-picker').value;
			monaco.editor.setTheme(themeTbl[newTheme]);
			var name = username + "_ide_theme";
			window.localStorage.setItem(name, newTheme);
			if (editor) {
				editor.layout();
			}
		}

		function changeFontsize() {
			var fontSize = document.getElementById('fontsize-picker').value;
			editor.updateOptions({
				fontSize: fontSize+"px"
			});
			var name = username + "_ide_fontsize";
			window.localStorage.setItem(name, fontSize);
			if (editor) {
				editor.layout();
			}
		}

		function changeLanguage(langIndex) {
			var lang = document.getElementById('select_lang').value;
			editor.updateOptions({
				language: langMap[lang],
			});
			if (editor) {
				editor.layout();
			}
		}

		function changeWordWrap() {
			var wordWrap = 'wordWrapColumn';
			var wordWrapMinified = 'true';
			var wordWrapColumn = document.getElementById('wordwrap-column').value;
			if (wordWrapColumn == '0') {
				wordWrap = 'off';
				wordWrapMinified = 'false';
			}
			editor.updateOptions({
				wordWrap: wordWrap,
				wordWrapColumn: wordWrapColumn,
				wordWrapMinified: wordWrapMinified,
			});

			name = username + "_ide_wordwrapcolume";
			window.localStorage.setItem(name, wordWrapColumn);
			if (editor) {
				editor.layout();
			}
		}
		function getElementById(id) {
			return document.getElementById(id);
		}

		var oBox = getElementById("problem-box");
		var oLeft = getElementById("problem-box-left");
		var oRight = getElementById("problem-box-right");
		var oDragbar = getElementById("problem-drag-bar");
		var oTestBox = getElementById("test-box");
		var oHeaderNavbar = getElementById("header-navbar");
		var oBottombarLeft = getElementById("bottom-bar-left");
		var oBottombarRight = getElementById("bottom-bar-right");
		var oIdeBoxNav = getElementById("ide-box-nav");
		var oTestBoxNavbar = getElementById("test-box-nav");
		var oTestInput = getElementById("input");
		var oTestOutput = getElementById("output");
		var oSrc = getElementById("source");
		var oProblemContent = getElementById("problem-content");
		var oIdeBox = getElementById("ide-box");

		function refleshSize() {
			oLeft.style.height = window.innerHeight - oHeaderNavbar.offsetHeight - oIdeBoxNav.offsetHeight + "px";
			oRight.style.height = window.innerHeight - oHeaderNavbar.offsetHeight + "px";
			oRight.style.left = oDragbar.offsetLeft + oDragbar.offsetWidth + "px";
			oRight.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth + "px";
			oProblemContent.style.height = window.innerHeight - oHeaderNavbar.offsetHeight -
				oBottombarLeft.offsetHeight - oIdeBoxNav.offsetHeight + "px";
			oBottombarLeft.style.width = oDragbar.offsetLeft + "px";
			oBottombarRight.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth + "px";
			oSrc.style.top = oHeaderNavbar.offsetHeight + oIdeBoxNav.offsetHeight + "px";
			oSrc.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth + "px";
			oSrc.style.height = window.innerHeight - oHeaderNavbar.offsetHeight - oTestBox.offsetHeight -
				oBottombarRight.offsetHeight - oIdeBoxNav.offsetHeight + "px";
			oTestInput.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth - 39 + "px";
			oTestOutput.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth - 39 + "px";
			oIdeBox.style.height = window.innerHeight - oHeaderNavbar.offsetHeight -
				oIdeBoxNav.offsetHeight - oBottombarRight.offsetHeight + "px";
			if (editor) {
				editor.layout();
			}
		}


		var problemMini = false;
		var sourceMini = false;
		var oDragbarLeft = oDragbar.offsetLeft;
		function problemMiniSize(left) {
			oDragbar.style.left = oLeft.style.width = left + "px";
			oRight.style.width = oBox.clientWidth - left - oDragbar.offsetWidth + "px";
			oSrc.style.width = oBox.clientWidth - left - oDragbar.offsetWidth + "px";
			oBottombarLeft.style.width = left + "px";
			oBottombarRight.style.width = oBox.clientWidth - left - oDragbar.offsetWidth + "px";
			oTestInput.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth - 40 + "px";
			oTestOutput.style.width = window.innerWidth - oDragbar.offsetLeft - oDragbar.offsetWidth - 40 + "px";
			if (editor) {
				editor.layout();
			}
		}

		$(".problem-info-close").click(function () {
			problemMini = true;
			sourceMini = false;
			problemMiniSize(0);
		});

		$(".source-box-close").click(function () {
			sourceMini = true;
			problemMini = false;
			problemMiniSize(oBox.clientWidth - 13);
		});

		window.onload = function () {
			refleshSize();
			oDragbar.ondblclick = function (e) {
				if(!problemMini) {
					problemMini = true;
					problemMiniSize(0);
				} else {
					problemMini = false;
					problemMiniSize(oDragbarLeft);
				}
				return false;
			};
			oDragbar.onmousedown = function (e) {
				var disX = (e || event).clientX;
				oDragbar.left = oDragbar.offsetLeft;
				document.onmousemove = function (e) {
					var iT = oDragbar.left + ((e || event).clientX - disX);
					var e = e || window.event, tarnameb = e.target || e.srcElement;
					var maxT = oBox.clientWidth - oDragbar.clientWidth;
					oDragbar.style.margin = 0;
					if (iT <= 100) {
						problemMiniSize(0);
						return false;
					}
					if (oBox.clientWidth - iT - 1 <= 100) {
						problemMiniSize(oBox.clientWidth - 13);
						return false;
					}
					problemMiniSize(iT);
					return false;
				};

				document.onmouseup = function () {
					document.onmousemove = null;
					document.onmouseup = null;
					oDragbar.releaseCapture && oDragbar.releaseCapture();
				};
				oDragbar.setCapture && oDragbar.setCapture();
				return false;
			};
			oTestBoxNavbar.onmousedown = function (e) {
				var disY = (e || event).clientY;
				oTestBoxNavbar.top = oTestBoxNavbar.offsetTop;

				document.onmousemove = function (e) {
					var iT = oTestBoxNavbar.top + ((e || event).clientY - disY);
					var e = e || window.event, tarnameb = e.target || e.srcElement;
					var maxT = oBox.clientHeight;
					oTestBoxNavbar.style.margin = 0;
					if (iT <= oHeaderNavbar.clientHeight + oIdeBoxNav.clientHeight) {
						return false;
					}
					if (oBox.clientHeight - iT <= oBottombarRight.clientHeight + oTestBoxNavbar.clientHeight) {
						return false;
					}

					oTestBoxNavbar.style.top = iT + "px";
					oTestBox.style.height = oBox.clientHeight - iT - oTestBoxNavbar.clientHeight - oBottombarRight.clientHeight + "px";
					oTestInput.style.height  = oBox.clientHeight - iT - oTestBoxNavbar.clientHeight - oBottombarRight.clientHeight - 20 + "px";
					oTestOutput.style.height  = oBox.clientHeight - iT - oTestBoxNavbar.clientHeight - oBottombarRight.clientHeight - 40 + "px";
					oSrc.style.height =  iT - oHeaderNavbar.clientHeight - oIdeBoxNav.clientHeight + "px";

					if (editor) {
						editor.layout();
					}
					return false
				};

				document.onmouseup = function () {
					document.onmousemove = null;
					document.onmouseup = null;
					oTestBoxNavbar.releaseCapture && oTestBoxNavbar.releaseCapture()
				};
				oTestBoxNavbar.setCapture && oTestBoxNavbar.setCapture();
				return false
			};
		};
		window.onresize = function () {
			refleshSize();
		}

		var oInputMenu = document.getElementById("test-nav-tab-input");
		var oOutputMenu = document.getElementById("test-nav-tab-output");
		var oInputBox = document.getElementById("test-box-tb-input");
		var oOutputBox = document.getElementById("test-box-tb-output");
		function tabShowSwitch(input) {
			if (input == 1) {
				oInputBox.style.display = "inline";
				oOutputBox.style.display = "none";
				oInputMenu.setAttribute("class", "test-box-nav-tab test-box-nav-tab-cur");
				oOutputMenu.setAttribute("class", "test-box-nav-tab");
			} else {
				oInputBox.style.display = "none";
				oOutputBox.style.display = "inline";
				oInputMenu.setAttribute("class", "test-box-nav-tab");
				oOutputMenu.setAttribute("class", "test-box-nav-tab test-box-nav-tab-cur");
			}
		}
		oInputMenu.addEventListener("click", function () {
			tabShowSwitch(1);
		});
		oOutputMenu.addEventListener("click", function () {
			tabShowSwitch(0);
		});

		function StatusQueryAckProc(data) {
			for ( var i = 0; i < 1; i++) {
				if (data.status[i].verdictId > 5) {
					var status_description = "";
					if (data.status[i].testCase > 0) {
						status_description = data.status[i].status_description + " on test " + data.status[i].testCase;
					} else {
						status_description = data.status[i].status_description;
					}
					$("#output-status").html("<span style='color: red'>" + status_description + "</span>" +
						"<span style='color: grey'>" + ", time: " + data.status[i].time + " ms" +
						", memory: " + data.status[i].memory + " kb." + "</span>");
					document.getElementById('output').value = "";
					return true;
				}
				if (data.status[i].verdictId == 5) {
					$("#output-status").html("<span style='color: green'>" + data.status[i].status_description + "</span>" +
						"<span style='color: grey'>" + ", time: " + data.status[i].time + " ms" +
						", memory: " + data.status[i].memory + " kb." + "</span>");
					document.getElementById('output').value = "";
					return true;
				}

				/* running */
				if (data.status[i].verdictId == 4) {
					if (data.status[i].testCase > 0) {
						document.getElementById('output').value = data.status[i].status_description + " on test "
							+ data.status[i].testCase;
					} else {
						document.getElementById('output').value = data.status[i].status_description;
					}
					return false;
				}

				if (data.status[i].verdictId == 3) {
					$("#output-status").html("<span style='color: blue'>" + data.status[i].status_description + "</span>");

					$.getJSON("viewcompileinfo",{solutionId: data.status[i].solutionId},function(json){
						if (json.success != true) {
							document.getElementById('output').value = "Get compile infomation failed."
							return false;
						}
						document.getElementById('output').value = json.errorInfo;
					});
					return true;
				}
				if (data.status[i].verdictId < 3) {
					document.getElementById('output').value = data.status[i].status_description;
					return false;
				}
			}
			return false;
		}

		function SubmitCheck(sessionId) {
			a = new Array();
			a.push( sessionId );

			if( a.length > 0 ){
				$.ajax({type : "POST",
					url : "/api/status/query",
					data : "ids=" + a.join(','),
					dataType : 'json',
					success : function(data) {
						var res = StatusQueryAckProc(data);
						if (res == false) {
							setTimeout(function () { SubmitCheck(sessionId); }, 2000);
						} else {
							$("#submitsolution").removeAttr("disabled");
						}
					}
				});
			}
		}
		function TestCheck(sessionId, cnt) {
			if (cnt > 0) {
				cnt = cnt - 1;
				if (cnt == 0) {
					$("#output-status").html("<span style='color: red'>" + "Test timeout, please try again." + "</span>");
					$('#runsolution').removeAttr("disabled");
					$('#verify-problem').removeAttr("disabled");
					return true;
				}

				if (cnt % 2 == 0) {
					setTimeout(function () { TestCheck(sessionId, cnt); }, 1000);
				} else {
					$.post(
						"/api/submit/check", { sessionId: sessionId }, function (result) {
							if (result.code == 200) {
								if (result.data.verdict == "pending") {
									setTimeout(function () { TestCheck(sessionId, cnt); }, 1000);
									return false;
								}

								if (result.data.verdict == "Compilation Error") {
									$("#output-status").html("<span style='color: blue'>" + result.data.verdict + "</span>");
									document.getElementById('output').value = result.data.compile_error;
								} else if (result.data.verdict == "Accepted"){
									$("#output-status").html("<span style='color: green'>" + "Run finish" + "</span>" +
										"<span style='color: grey'>" + ", time: " + result.data.time + " ms" +
										", memory: " + result.data.memory + " kb." + "</span>");
									document.getElementById('output').value = result.data.output;
								} else {
									$("#output-status").html("<span style='color: red'>" + result.data.verdict + "</span>" +
										"<span style='color: grey'>" + ", time: " + result.data.time + " ms" +
										", memory: " + result.data.memory + " kb." + "</span>");
									document.getElementById('output').value = result.data.output;
								}
								$("#runsolution").removeAttr("disabled");
								$("#verify-problem").removeAttr("disabled");
							}
						},
						"json"
					);
				}
			}
		};
		$(".verify-problem").click(function () {
			$('#verify-problem').attr('disabled', 'disabled');

			tabShowSwitch(0);
			consoleSwitch(1);
			SaveCode();
			$("#output-status").html("<img src='/img/loader.gif'>");
			document.getElementById('output').value = "";

			var source = editor.getValue();
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			var formData = { "mode": 0, "contestId": contestId, "problemId": problemId,
				"language": language, "source": source}
			$.ajax({
				type : "post",
				url : "/api/submit/verify",
				data : JSON.stringify(formData),
				contentType:"application/json",
				dataType : "json",
				success : function(data) {
					if (data.code != 200) {
						$("#output-status").html("<span style='color: red'>" + data.msg  + "</span>");
						$("#verify-problem").removeAttr("disabled");
					} else {
						setTimeout(function () { TestCheck(data.data, 60); }, 1000);
					}
				}
			});
			return false;
		});
		$(".run-solution").click(function () {
			$('#runsolution').attr('disabled', 'disabled');

			tabShowSwitch(0);
			consoleSwitch(1);
			SaveCode();
			$("#output-status").html("<img src='/img/loader.gif'>");
			document.getElementById('output').value = "";

			var source = editor.getValue();
			var input = document.getElementById('input').value;
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			var formData = { "mode": 0, "contestId": contestId, "problemId": problemId,
				"language": language, "source": source, "input": input }
			$.ajax({
				type : "post",
				url : "/api/submit/test",
				data : JSON.stringify(formData),
				contentType:"application/json",
				dataType : "json",
				success : function(data) {
					if (data.code != 200) {
						$("#output-status").html("<span style='color: red'>" + data.msg  + "</span>");
						$("#runsolution").removeAttr("disabled");
					} else {
						setTimeout(function () { TestCheck(data.data, 60); }, 1000);
					}
				}
			});
			return false;
		});
		$(".submit-solution").click(function () {
			$('#submitsolution').attr('disabled', 'disabled');
			SaveCode();
			tabShowSwitch(0);
			consoleSwitch(1);
			$("#output-status").html("<img src='/img/loader.gif'>");
			document.getElementById('output').value = "";

			var source = editor.getValue();
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			var formData = { "mode": 1, "contestId": contestId, "problemId": problemId,
				"language": language, "source": source, "input": "" }
			$.ajax({
				type : "post",
				url : "/api/submit",
				data : JSON.stringify(formData),
				contentType:"application/json",
				dataType : "json",
				success : function(data) {
					if (data.code != 200) {
						showStatusTab(1);
						$("#output-status").html("<span style='color: red'>" + data.msg  + "</span>");
						$('#submitsolution').removeAttr("disabled");
					} else {
						showStatusTab(1);
						$("#output-status").html("<span style='color: green'>" + "Submit solution successfully." + "</span>");
						$('#submitsolution').removeAttr("disabled");
					}
				}
			});
			return false;
		});
		$(".submit-contest-solution").click(function () {
			$('#submitsolution').attr('disabled', 'disabled');
			SaveCode();
			tabShowSwitch(0);
			consoleSwitch(1);
			$("#output-status").html("<img src='/img/loader.gif'>");
			document.getElementById('output').value = "";

			var source = editor.getValue();
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			$.post("/api/submit", { submit: 1, contestId: contestId, problemId: problemId, language: language, source: source }, function (data) {
				if (data.success != true) {
					consoleSwitch(1);
					showStatusTab(1);
					$("#output-status").html("<span style='color: red'>" + data.error + "</span>");
					$("#submitsolution").removeAttr("disabled");
				} else {
					//window.location = "contest/" + contestId + "/status";
					showStatusTab(1);
					oLoader.style.display = "none";
					$("#output-status").html("<span style='color: green'>" + "Submit solution successfully." + "</span>");
					$('#submitsolution').removeAttr("disabled");
				}
			}, "json");
			return false;
		});

		/* listenning  code  change */
		editor.onDidChangeModelContent(function (e) {

		});

		/* load the last language option */
		function LoadLanguage() {
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var name = username + "_lang_" + contestId + "_" + problemId;
			var lang_opt = window.localStorage.getItem(name);
			if (lang_opt != null) {
				$('#select_lang').val(lang_opt);
				$('#select_lang').width(60 + $('#select_lang option:selected').html().length);
			}
		}
		function SaveLanguage() {
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var lang = document.getElementById('select_lang').value;
			var name = username + "_lang_" + contestId + "_" + problemId;
			window.localStorage.setItem(name, lang);
		}
		LoadLanguage();
		SaveLanguage();

		function loadDefaultTemplate(language) {
			editor.setValue("");
			$.getJSON("/api/submit/template", {language: language}, function(json) {
				if (json.code != 200) {
					return;
				}
				editor.setValue(json.data);
			},"json");
		}

		function LoadCode() {
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			var name = username + "_code_" + contestId + "_" + problemId + "_" + language;
			var source = window.localStorage.getItem(name);
			if (source == null) {
				/* 缓存没有，从默认模板加载 */
				loadDefaultTemplate(language);
			} else {
				editor.setValue(source);
			}
		}
		/* read code from cookie */
		LoadCode();
		$("#select_lang").change(function (e) {
			SaveLanguage();
			LoadCode();
		});
		function SaveCode() {
			var source = editor.getValue();
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			var language = document.getElementById('select_lang').value;
			var name = username + "_code_" + contestId + "_" + problemId + "_" + language;
			window.localStorage.setItem(name, source);
		}
		/* auto save code to cookie */
		function SaveCodeTimer() {
			SaveCode();
			setTimeout(function () { SaveCodeTimer(); }, 5000);
		}
		setTimeout(function () { SaveCodeTimer(); }, 5000);

		/* console menu */
		var on = 0;
		var oConsoleCaert = document.getElementById("consoleCaert");
		var oConsoleMenu = document.getElementById("consoleMenu");
		function consoleSwitch(forceOn) {
			if (on == 1 && forceOn == 0) {
				oTestBox.style.display = "none";
				oConsoleCaert.setAttribute("class", "caret-down");
				oSrc.style.height = window.innerHeight - oHeaderNavbar.offsetHeight -
					oBottombarRight.offsetHeight - oIdeBoxNav.offsetHeight + "px";
				on = 0;
			} else {
				oTestBox.style.display = "inline";
				oConsoleCaert.setAttribute("class", "caret-up");
				oSrc.style.height = window.innerHeight - oHeaderNavbar.offsetHeight - oTestBox.offsetHeight -
					oBottombarRight.offsetHeight - oIdeBoxNav.offsetHeight + "px";
				on = 1;
			}
			if (editor) {
				editor.layout();
			}
		}

		oConsoleMenu.addEventListener("click", function () {
			consoleSwitch(0);
		});

		$(".ide-setting").click(function() {
			var scrollTop = window.pageYOffset||document.documentElement.scrollTop || document.body.scrollTop;
			var topPosInner = 60 + scrollTop;
			var leftPosIner = ($(document.body).width() - 672)/2;
			document.getElementById('pop-inner-div-ide-setting').style.top= topPosInner +'px';
			document.getElementById('pop-inner-div-ide-setting').style.left= leftPosIner +'px';
			document.getElementById('pop-div-ide-setting').style.top= scrollTop +'px';
			document.documentElement.style.overflowY = 'hidden';

			$(".pop-div-ide-setting").fadeIn();
			$(".pop-inner-div-ide-setting").fadeIn();
			return false;
		});
		$(".pop-div-ide-setting").click(function(){
			$(".pop-div-ide-setting").fadeOut();
			$(".pop-inner-div-ide-setting").fadeOut();
			document.documentElement.style.overflowY = 'scroll';
		});
		var timeFormatSeconds = function(time) {
			var d = time ? new Date(time) : new Date();
			var year = d.getFullYear();
			var month = d.getMonth() + 1;
			var day = d.getDate();
			var hours = d.getHours();
			var min = d.getMinutes();
			var seconds = d.getSeconds();

			if (month < 10) month = '0' + month;
			if (day < 10) day = '0' + day;
			if (hours < 10) hours = '0' + hours;
			if (min < 10) min = '0' + min;
			if (seconds < 10) seconds = '0' + seconds;
			return (year + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + seconds);
		}

		var showStatus = 0;
		var showProblem = 1;
		var showEditorial = 0;
		var oLoader = document.getElementById("problem-status-loader");
		var oProblemInfo = document.getElementById("problem-information");
		var oProblemEditorial = document.getElementById("problem-editorial");
		var oProblemStatus = document.getElementById("problem-status");
		function showProblemTab() {
			oProblemInfo.style.display = "inline";
			oProblemStatus.style.display = "none";
			oProblemEditorial.style.display = "none";
			showStatus = 0;
			showEditorial = 0;
			showProblem = 1;
		}

		var editorialPageNum = 1;
		function showProblemEditorialTab() {
			oProblemEditorial.style.display = "inline";
			oProblemStatus.style.display = "none";
			oProblemInfo.style.display = "none";
			showStatus = 0;
			showProblem = 0;
			showEditorial = 1;

			var problemId = document.getElementById('problemId').value;
			$.getJSON("/api/problem/editorial/query",{problemId:problemId, pageNum:editorialPageNum},function(json) {
				if (json.code != 200) {
					return false;
				}

				$(".problem-editorial-num").html(json.data.total);

				var html = "";
				html += "<div class='editorial-items'>"
				for (var i = 0; i < json.data.list.length; i++) {
					var item = json.data.list[i];
					html += "<div class='editorial-item' messageId='"+item.message_id+"'>"
					html += "<span class='editorial-item-avatar'>"
						+ "<a href='/profile/" + item.user.username + "' class='rated-user user-rate-"
						+ item.user.rate +" user-tip' user='" + item.user.username + "'>"
						+ "<img class='ss-avatar' src='" + item.user.avatar +"'>"
						+ "</a></span>"
					html += "<div class='editorial-item-content'>"
						+ "<a href='/profile/" + item.user.username + "' class='rated-user user-rate-"
						+ item.user.rate +" user-tip' user='" + item.user.username + "'>"
						+ item.user.username
						+ "</a><span style='color: grey;margin-left: 12px;'>"+item.friendly_Date+"</span>"
						+ "<div class='title'>"+item.title
						if (item.orderNum > 0) {
							html += "<svg class=\"topic-svg-icon\" viewBox=\"0 0 1024 1024\" p-id=\"24678\" ><path d=\"M691.2 512V153.6h44.8V64h-448v89.6h44.8V512L243.2 601.6v89.6h232.96V960h71.68v-268.8h232.96V601.6z\" fill=\"#CE4E36\" p-id=\"24679\"></path></svg>"
						}
					html += "</div>"
						+ "<div class='content'>"+item.content_abstract+"</div>"
					html += "<div class='tags'>"
					for (var j = 0; j < item.tags.length; j++) {
						html += "<span><a href='' class='tag' tag='" + item.tags[j].name + "'>"+item.tags[j].name+"</a></span>"
					}
					html += "</div>";

					html += "<div class='editorial-item-opts'>"
					html += "<span class='div-icon-svg' title='阅读'>"
						+ "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" class=\"icon-svg\"><g><path d=\"M8.75 21V3h2v18h-2zM18 21V8.5h2V21h-2zM4 21l.004-10h2L6 21H4zm9.248 0v-7h2v7h-2z\"></path></g></svg>"
						+ "<span class='opts-item'>"+item.views+"</span></span>"
					html += "<span class='div-icon-svg' title='评论'>"
						+ "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" class=\"icon-svg\"><g><path d=\"M1.751 10c0-4.42 3.584-8 8.005-8h4.366c4.49 0 8.129 3.64 8.129 8.13 0 2.96-1.607 5.68-4.196 7.11l-8.054 4.46v-3.69h-.067c-4.49.1-8.183-3.51-8.183-8.01zm8.005-6c-3.317 0-6.005 2.69-6.005 6 0 3.37 2.77 6.08 6.138 6.01l.351-.01h1.761v2.3l5.087-2.81c1.951-1.08 3.163-3.13 3.163-5.36 0-3.39-2.744-6.13-6.129-6.13H9.756z\"></path></g></svg>"
						+ "<span class='opts-item'>"+item.comments+"</span></span>"
					html += "</div>"

					html += "</div>"
					html += "</div>"
				}
				html += "</div>"
				$(".problem-editorial-list").html(html);
			});
		}
		$(document).on("click",".editorial-item",function() {
			var messageId = $(this).attr("messageId");
			window.open("/topic/"+messageId, '_blank');
			return false;
		});

		var statusOver = 0;
		var fromSolutionId = 2147483647;
		function showStatusTab(force) {
			if (statusOver == 0) {
				oLoader.style.display = "inline";
			}
			if (force == 1) {
				fromSolutionId = 2147483647;
				statusOver = 0;
				$(".status tr:gt(0)").remove();
			}

			oProblemInfo.style.display = "none";
			oProblemEditorial.style.display = "none";
			oProblemStatus.style.display = "inline";
			showStatus = 1;
			showProblem = 0;
			showEditorial = 0;
			var opt="";
			var problemId = document.getElementById('problemId').value;
			var contestId = document.getElementById('contestId').value;
			$.getJSON("/api/submission/query",{pageSize:100, problemId:problemId, contestId:contestId, fromSolutionId:fromSolutionId, username:username},function(json){
				if (json.code != 200) {
					return false;
				}
				if (json.data.length == 0 && statusOver == 0 && fromSolutionId == 2147483647) {
					statusOver = 1;
					var htmlList = "";
					htmlList += '<tr><td class=\"left-item dark\" colSpan=\"20\" style=\"text-align: left;\">There is no records.</td></tr>';
					$(".status tr:last").after(htmlList);
				}

				for ( var i = 0; i < json.data.length; i++) {
					fromSolutionId = json.data[i].solution_id;
					var htmlList = "";
					if (i%2 == 1) {
						htmlList += '<tr class=\"dark\">';
					} else {
						htmlList += '<tr>';
					}
					htmlList += '<td class=\"left-item verdict';
					if (json.data[i].verdict == 5) {
						htmlList += ' verdict_ac';
					} else if (json.data[i].verdict == 3) {
						htmlList += ' verdict_ce';
					} else if (json.data[i].verdict == 10) {
						htmlList += ' verdict_pe';
					} else if (json.data[i].verdict < 5) {
						htmlList += ' verdict_prev';
					} else {
						htmlList += ' verdict_other';
					}
					htmlList += '\" id=status_' + json.data[i].solution_id ;
					htmlList += ' status='+ json.data[i].verdict ;
					htmlList += ' manual=0 ';

					htmlList += '><a solutionId=' + json.data[i].solution_id + ' class=\"view-source\" href=\"/view-source/' +
						json.data[i].solution_id + '\" title=\"source\" target=\"_blank\">' +
						json.data[i].status_description +'</a></td>';
					htmlList += '<td class=\"time\"  id=\"time_' + json.data[i].solution_id + '\">' + json.data[i].time +' ms</td>';
					htmlList += '<td class=\"memory\" id=\"memory_' + json.data[i].solution_id + '\">' + json.data[i].memory +' kb</td>';
					htmlList += '<td class=\"language\">'+ json.data[i].language_name +'</td>';
					htmlList += '<td class=\"date\" title=\"'+ timeFormatSeconds(json.data[i].submit_date)+ '\">' +
						json.data[i].friendlySubmitDate +'</td>';
					$(".status tr:last").after(htmlList);
				}

				OnlineJudge.statusReflesh();
			});
		}

		var oProblemContentNav= document.getElementById("problem-box-nav-content");
		var oProblemEditorialNav= document.getElementById("problem-box-nav-editorial");
		var oProblemStatusNav= document.getElementById("problem-box-nav-status");
		oProblemContentNav.addEventListener("click", function () {
			showProblemTab();
			oProblemContentNav.setAttribute("class", "nav_menu current");
			oProblemStatusNav.setAttribute("class", "nav_menu");
			oProblemEditorialNav.setAttribute("class", "nav_menu");
		});
		oProblemEditorialNav.addEventListener("click", function () {
			showProblemEditorialTab();
			oProblemContentNav.setAttribute("class", "nav_menu");
			oProblemEditorialNav.setAttribute("class", "nav_menu current");
			oProblemStatusNav.setAttribute("class", "nav_menu");
		});
		oProblemStatusNav.addEventListener("click", function () {
			showStatusTab(0);
			oLoader.style.display = "none";
			oProblemStatusNav.setAttribute("class", "nav_menu current");
			oProblemContentNav.setAttribute("class", "nav_menu");
			oProblemEditorialNav.setAttribute("class", "nav_menu");
		});

		var flag = 0;
		function updateTable(scrollTop) {
			showStatusTab(0);
			flag = 0;
			oLoader.style.display = "none";
			document.querySelector('.problem-content').scrollTop = scrollTop;
		};
		document.querySelector('.problem-content').addEventListener("scroll", function () {
			if (showStatus == 0) {
				return false;
			}
			var clientHeight = this.clientHeight;
			var scrollTop = this.scrollTop;
			var scrollHeight = this.scrollHeight;
			if (scrollHeight - scrollTop - clientHeight <= 3) {
				if (flag == 0) {
					flag = 1;
					this.scrollTop = scrollTop - 10;
					oLoader.style.display = "inline";
					setTimeout(function () { updateTable(scrollTop); }, 500);
				}
			}
		});

		$(".load-default-template").click(function(){
			if(confirm('WARNING! This operation will overwrite your code with default template.')){
				var language = document.getElementById('select_lang').value;
				loadDefaultTemplate(language);
			}
		});

		$('#select_lang').change(function(){
			$(this).width(60 + $('#select_lang option:selected').html().length);
		});
	});
});